let shareData = {
  title: 'GNC',
  desc: 'DNC DESC',
  link: location.href.split('#')[0],
  imgUrl: $('#share_img').prop('src')
};

let authkey = getQueryString('authkey');
let mpqrcode_url = getQueryString('mpqrcode_url');
let openid = getQueryString('openid') || $.cookie('openid');
// let DOAIM_PREFIX = 'http://locahost:8888/wechat/h5/';
let DOAIM_PREFIX = 'http://www.createcdigital.com/createc-new/h5/gnc-h5-20181217/';

let API_SUBMIT_YANSHEN_URL = DOAIM_PREFIX + 'submit-yanshen.php';

let API_TAKE_FL_YANSEH_TOTAL_URL = DOAIM_PREFIX + 'take-fl-yanshen-total.php';
let API_LOTTERY_DRAW = DOAIM_PREFIX + 'lottery-draw.php';
let API_GNCFORM_URL = DOAIM_PREFIX + 'gncform.php';
let API_GETOPENID_URL = DOAIM_PREFIX + 'getopenid.php';
let MAIN = $('#main');
let landing_HTML = $('#landing_HTML').html();
let home_HTML = $('#home_HTML').html();
let home2_HTML = $('#home2_HTML').html();
let yanshen_HTML = $('#yanshen_HTML').html();
let yehuangsu_HTML = $('#yehuangsu_HTML').html();
let gnccoupon_HTML = $('#gnccoupon_HTML').html();
let gncform_HTML = $('#gncform_HTML').html();

let start = '.p2-btn';
let btn_prev_yanshen = '#prev_yanshen';
let send_yanshen = '#send_yanshen';
let next_yanshen = '#next_yanshen';

let yanshenSel = store.get('yanshenSel');
let yanshenList = ['猥琐', '帅', '白眼', '爱心'];

let yanshengImgIdPrefix = '#yanshenNo';
let yanshengImgLightList = [
  'images/猥琐_1.png',
  'images/帅_1.png',
  'images/白眼_1.png',
  'images/爱心_1.png',
];

let yanshenScreen = '#yanshenScreen';
let scale = DPR();

let restyanshen = '#restyanshen';
let shareyanshen = '#shareyanshen';
let shenling = '#shenling';
let yehuangsuinfo = '#yehuangsuinfo';
let go_gnccoupon = '#go_gnccoupon';
let submit_yehuangsu = '#submit_yehuangsu';
let is4light = false;
let reward = 'yehuangsu';

let mpqrcode = '#mpqrcode';

let go_gnccoupon_url = 'https://www.baidu.com';

let user = '#name';
let mobile = '#phone';
let address = '#add';

let yanshen4 = '.yanshen4';

let gncform = '#gncform';

let rule_btn = '.rule';

let xhrSY = null;

let xhrFL = $.post(API_TAKE_FL_YANSEH_TOTAL_URL, {openid: openid});

let xhrLD = null;

let lightNum = 3;

let IndexPage = 'landing';

let coupon

// let swiper = new Swiper('.A', {
//   direction: 'vertical',
//   noSwipingClass: 'stop-swiping',
//   effect: 'fade',
//   onSlideChangeStart: function (swiper) {
//     var page = swiper.activeIndex
//     if (page == 1) {
//
//     }
//   }
// });

$.post(API_GETOPENID_URL, {authkey: authkey}, function (res) {
  openid = res.openid;
  mpqrcode_url = res.url;
  alert(openid)
});


Q.reg('landing', function () {
  MAIN.html(landing_HTML);
  setTimeout(function () {
    landingPage()

  }, 2000);
});

Q.reg('home', function () {
  MAIN.html(home_HTML);
  homePgae();
});
Q.reg('home2', function () {
  MAIN.html(home2_HTML);
  homePgae();
});


Q.reg('yanshen', function () {
  MAIN.html(yanshen_HTML);
  yanshenPage()
});

Q.reg('yehuangsu', function () {
  MAIN.html(yehuangsu_HTML);
  yehuangsuPage();
  gncformPage()
});

Q.reg('gncform', function () {
  MAIN.html(gncform_HTML);
  gncformPage();
});

Q.reg('gnccoupon', function () {
  MAIN.html(gnccoupon_HTML);
  gnccouponPage();
});

Q.init({
  index: getH5Progress()/* 首页地址 */
});

function landingPage() {
  $('.page1').hide();
  $('.page2').fadeIn();
  $(start).click(function () {
    Q.go('home2')
  });

  $(rule_btn).click(function () {
    $('.rule-conten').fadeIn();
  });
  $('.rule-conten').click(function () {
    $('.rule-conten').fadeOut();
  })

}

function homePgae() {

  let mySwiper = new Swiper('.swiper-container-2', {
    // direction: 'vertical',
    prevButton: '.left',
    nextButton: '.right',
    onSlideChangeStart: function (swiper) {
      var page = swiper.activeIndex
      if (page == 1) {

      }
    }
  });


  $(btn_prev_yanshen).click(function () {
    mySwiper.slidePrev();
  });


  $(send_yanshen).click(function () {
    yanshenSel = mySwiper.activeIndex;
    xhrSY = $.post(API_SUBMIT_YANSHEN_URL, {openid: openid, firstlight: yanshenSel});
    // alert(yanshenList[yanshenSel]);

    store.set('yanshenSel', mySwiper.activeIndex);
    Q.go('yanshen')
  });


  $(next_yanshen).click(function () {
    mySwiper.slideNext();
  });
}

function yanshenPage() {
  let yanshengImgId = yanshengImgIdPrefix + (yanshenSel + 1);
  $(yanshengImgId).attr('src', changeYanshen());
  $(yanshengImgId).attr('data-light', 1);
  $(mpqrcode).qrcode({
    text: mpqrcode_url ? mpqrcode_url : '',
    width: $(mpqrcode).width(),
    height: $(mpqrcode).height(),
  });

  xhrFL.done(function (res) {
    if (res.code !== 0) {

      return
    }
    let count = res.data.count;
    if (count == lightNum) {
      is4light = true
    }

    $(yanshen4).find('.yanshen').each(function (i, e) {

      if (count === 0) {

        return
      }
      if ($(e).attr('data-light') === '0') {
        $(e).attr('data-light', 1);
        $(e).attr('src', changeFlYanshen($(e)));
        count--
      }

    })


  });


  // loading带文字
  layer.open({
    type: 2
    , content: '加载中'
    , time: 2
    , end: function () {
      // convert2img();
      store.set('h5progress', 'yanshen');
    }
  });


  $(restyanshen).click(function () {
    Q.go('home2');
    store.remove('h5progress')
  });

  $(shareyanshen).click(function () {
    alert('分享浮层')

    shareData.url = $('<a href="./">').prop('href') + 'custom.html?orginopenid' + openid;
    shareFunc()
  });

  $(shenling).click(function () {
    if (is4light) {
      xhrLD = ajaxLotteryDraw();
      xhrLD.done(function (res) {
        if (res.yes === reward) {
          Q.go('yehuangsu')
        } else {
          Q.go('gnccoupon')
        }
      })
    } else {
      alert('全部点亮可以领取！')
    }


  });

  function changeYanshen() {
    return yanshengImgLightList[yanshenSel]
  }

  function changeFlYanshen($e) {
    let oSrc = $e.attr('src');
    let nSrc = oSrc.replace('0', '1');

    return nSrc
  }


  function convert2img() {
    let yanshenScreenElem = $(yanshenScreen)[0];
    html2canvas(yanshenScreenElem).then(function (canvas) {
      let img = Canvas2Image.convertToJPEG(canvas, canvas.width, canvas.height);
      $(img).css({
        'width': canvas.width / scale + 'px',
        'height': canvas.height / scale + 'px',
        'vertical-align': 'middle',
      });
      img = $('<div>').append(img);
      $(yanshenScreen).html(img.html());
      console.log(img)
    })
  }


}

function yehuangsuPage() {
  store.set('h5progress', 'yehuangsu');
  $(yehuangsuinfo).click(function () {
    $(gncform).fadeIn();
  });
}

function gnccouponPage() {
  store.set('h5progress', 'gnccoupon');

  
  $(go_gnccoupon).click(function () {
    $('<a >').attr('href', go_gnccoupon_url)[0].click();
  });
}

function gncformPage() {
  $('.gncform-close').click(function () {
    $(gncform).fadeOut();
  });
  $(submit_yehuangsu).click(function () {
    let userVal = $(user).val();
    let mobileVal = $(mobile).val();
    let addressVal = $(address).val();
    userVal = $.trim(userVal);
    mobileVal = $.trim(mobileVal);
    addressVal = $.trim(addressVal);

    if (userVal === '') {
      showMsg('请填写姓名');
      return
    }
    if (mobileVal === '') {
      showMsg('请填写手机号');
      return
    }
    if (!isMobile(mobileVal)) {
      showMsg('手机号格式不正确');
      return
    }

    if (addressVal === '') {
      showMsg('请填写地址');
      return
    }

    $.post(API_GNCFORM_URL, {
      user: userVal,
      mobile: mobileVal,
      address: addressVal,
      openid: openid,
    }).done(function (res) {
      if (res.code !== 0) {
        alert(res.err);
        return
      }
      alert('提交成功');
      Q.go('gnccoupon')
    });


  })


}

function ajaxLotteryDraw() {
  return $.post(API_LOTTERY_DRAW);
}

function lotteryDraw() {
  let num = Math.floor(Math.random() * 10 + 1);
  if (num > 2) {
    return ''
  }
  return 'yehuangsu'
}

function isMobile(mobile) {
  var pattern = /^1[34578]\d{9}$/;
  if (pattern.test(mobile)) {
    return true
  }
  return false
}

function showMsg(msg) {
  layer.open({
    content: msg
    , skin: 'msg'
    , time: 2 //2秒后自动关闭
  });
}

/**
 * 根据window.devicePixelRatio获取像素比
 */
function DPR() {
  if (window.devicePixelRatio && window.devicePixelRatio > 1) {
    return window.devicePixelRatio;
  }
  return 1;
}

function getQueryString(name) {
  var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
  var r = window.location.search.substr(1).match(reg);
  if (r != null) return unescape(r[2]);
  return null;
}

function yanshenSelVal(k, v) {
}

function getH5Progress() {

  if (store.get('h5progress')) {
    return store.get('h5progress')
  }
  return IndexPage
}


$.ajax({
  url: 'http://www.createcdigital.com/createc-new/weChat/weChatApi.php',
  type: 'POST',
  async: true,
  data: {url: location.href.split('#')[0]},
  dataType: 'json',
  cache: false,
  success: function (data) {
    wx.config({
      debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
      appId: data['appId'], // 必填，公众号的唯一标识
      timestamp: data['timestamp'], // 必填，生成签名的时间戳
      nonceStr: data['nonceStr'], // 必填，生成签名的随机串
      signature: data['signature'],// 必填，签名
      jsApiList: ['checkJsApi', 'updateAppMessageShareData', 'updateTimelineShareData', 'onMenuShareAppMessage', 'onMenuShareTimeline', 'onMenuShareQQ', 'onMenuShareWeibo', 'onMenuShareQZone'] // 必填，需要使用的JS接口列表
    });

    shareFunc()

  }
});

function shareFunc() {
  wx.ready(function () {   //需在用户可能点击分享按钮前就先调用

    wx.checkJsApi({
      jsApiList: ['updateAppMessageShareData', 'updateTimelineShareData', 'onMenuShareAppMessage', 'onMenuShareTimeline', 'onMenuShareQQ', 'onMenuShareWeibo', 'onMenuShareQZone'], // 需要检测的JS接口列表，所有JS接口列表见附录2,
      success: function (res) {
        // 以键值对的形式返回，可用的api值true，不可用为false
        // 如：{"checkResult":{"chooseImage":true},"errMsg":"checkJsApi:ok"}
        // alert(JSON.stringify(res));
      }
    });

    wx.updateAppMessageShareData(shareData, function (res) {
//这里是回调函数
    });

    wx.updateTimelineShareData(shareData, function (res) {
//这里是回调函数
    });

    wx.onMenuShareAppMessage(shareData, function (res) {
//这里是回调函数
    });

    wx.onMenuShareTimeline(shareData, function (res) {
//这里是回调函数
    });
    wx.onMenuShareQQ(shareData, function (res) {
//这里是回调函数
    });
    wx.onMenuShareWeibo(shareData, function (res) {
//这里是回调函数
    });
    wx.onMenuShareQZone(shareData, function (res) {
//这里是回调函数
    });
  });

}



